package com.ss.android.caijing.stepcounterlib.store;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;

import com.ss.android.caijing.stepcounterlib.log.SSLog;
import com.ss.android.caijing.stepcounterlib.model.StepModel;
import com.ss.android.caijing.stepcounterlib.utils.Util;

/**
 * Created by zdh on 2017/10/13.
 */

public class StepDBManager {
    private static final String TAG = "StepDPManager";

    private static final String NAME_DB = "stepcount.db";
    private static final int VERSION_DB = 1;
    private static final String NAME_TABLE = "stepcount";

    private Context mContext;
    private SQLiteDatabase mDb;
    private volatile boolean mClosed = false;

    private static StepDBManager instance = null;
    private final static Object mObj = new Object();

    private interface FIELD {
        String AUTO_ID = "auto_id";
        String DATETIME = "datetime";
        String COUNT = "stepcount";
        String USERID = "userid";
    }

    private static final String[] STEP_COLOUMNS = {
            FIELD.DATETIME,
            FIELD.COUNT,
            FIELD.USERID
    };

    private StepDBManager(Context context) {
        this.mContext = context;
    }

    public static StepDBManager getInstance(Context context) {
        synchronized (mObj) {
            if (instance == null) {
                instance = new StepDBManager(context);
            }
        }
        return instance;
    }

    public static void closeDB() {
        synchronized (mObj) {
            if (instance != null) {
                instance.closeDatabase();
                instance = null;
            }
        }
    }

    private boolean isDbOpen() {
        if (mClosed)
            return false;
        if (mDb == null)
            mDb = openDb(mContext);
        if (mDb == null || !mDb.isOpen()) {
            return false;
        } else {
            return true;
        }
    }

    private void closeDatabase() {
        mClosed = true;
        try {
            if (mDb != null && mDb.isOpen()) {
                mDb.close();
                mDb = null;
            }
            mContext = null;
        } catch (Throwable tr) {
        }
    }

    private SQLiteDatabase openDb(Context context) {
        try {
            DatabaseHelper helper = new DatabaseHelper(context);
            return helper.getWritableDatabase();
        } catch (Throwable e) {
            // ignore
        }
        return null;
    }

    public synchronized void clearAllData() {
        if (!isDbOpen())
            return;
        try {
            mDb.delete(NAME_TABLE, null, null);
        } catch (Exception e) {
        }
    }

    public synchronized void clearTodayData() {
        if (!isDbOpen())
            return;
        try {
            String whereClause = FIELD.DATETIME + "=? ";
            String[] whereArgs = {String.valueOf(Util.getTodayTime())};
            mDb.delete(NAME_TABLE, whereClause, whereArgs);
        } catch (Exception e) {
        }
    }

    public synchronized void insertStepData(StepModel stepData) {
        if (!isDbOpen() || stepData == null)
            return;
        try {
            mDb.beginTransaction();
            ContentValues contentValues = encapsulateFeedbackColumns(stepData);
            String whereClause = FIELD.DATETIME + "=? and " + FIELD.USERID + "=?";
            String[] whereArgs = {String.valueOf(stepData.dateTime), stepData.userID};
            if (mDb.update(NAME_TABLE, contentValues, whereClause, whereArgs) <= 0)
                mDb.insert(NAME_TABLE, null, contentValues);
            mDb.setTransactionSuccessful();
        } catch (Exception e) {
        } finally {
            try {
                mDb.endTransaction();
            } catch (Exception e) {
            }
        }
    }

    private ContentValues encapsulateFeedbackColumns(StepModel item) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(FIELD.DATETIME, item.dateTime);
        contentValues.put(FIELD.USERID, item.userID);
        contentValues.put(FIELD.COUNT, item.stepCount);
        return contentValues;
    }

    public void deleteData(String userID, long date) {
        if (!isDbOpen() || TextUtils.isEmpty(userID) || date <= 0)
            return;
        try {
            mDb.beginTransaction();
            String whereClause = FIELD.DATETIME + "=? and " + FIELD.USERID + "=?";
            String[] whereArgs = {String.valueOf(date), userID};
            mDb.delete(NAME_TABLE, whereClause, whereArgs);
            mDb.setTransactionSuccessful();
        } catch (Exception e) {
        } finally {
            try {
                mDb.endTransaction();
            } catch (Exception e) {
            }
        }
    }

    public StepModel getStepModel(String userID, long date) {
        if (!isDbOpen() || TextUtils.isEmpty(userID) || date <= 0)
            return null;
        Cursor cursor = null;
        try {
            String whereClause = FIELD.DATETIME + "=? and " + FIELD.USERID + "=?";
            String[] whereArgs = {String.valueOf(date), userID};
            cursor = mDb.query(NAME_TABLE, STEP_COLOUMNS, whereClause, whereArgs, null, null, null);
            if (cursor != null && cursor.moveToNext()) {
                StepModel model = extraCursor(cursor);
                cursor.close();
                return model;
            }
        } catch (Exception e) {
            SSLog.i("getmodel", e.toString());
        } finally {
            try {
                if (cursor != null)
                    cursor.close();
            } catch (Exception e) {
                // ignore
            }
        }

        return null;
    }

    private StepModel extraCursor(Cursor cursor) {
        if (cursor == null || cursor.isClosed()) {
            return null;
        }
        StepModel model = new StepModel();
        model.userID = cursor.getColumnName(cursor.getColumnIndex(FIELD.USERID));
        model.dateTime = cursor.getLong(cursor.getColumnIndex(FIELD.DATETIME));
        model.stepCount = cursor.getInt(cursor.getColumnIndex(FIELD.COUNT));

        return model;
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {

        private final static String CreateFeedbackTable = "CREATE TABLE " + NAME_TABLE + " ("
                + FIELD.AUTO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + FIELD.DATETIME + " INTEGER NOT NULL DEFAULT 0,"
                + FIELD.COUNT + " INTEGER NOT NULL DEFAULT 0,"
                + FIELD.USERID + " VARCHAR"
                + " )";

        public DatabaseHelper(Context context) {
            super(context, NAME_DB, null, VERSION_DB);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CreateFeedbackTable);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }

}
